<template>
	<view class="vw100 minh100vh pb210 bgf6">
		
		<view class="px30 py20 bgfff mar-top-20">
			<view class="row a-center" v-if="addressInfo.name" @tap="toAddressList">
				<view class="flex1">
					<view class="ft32">
						<text>{{addressInfo.province}}{{addressInfo.city}}{{addressInfo.area}}{{addressInfo.address}}</text>
					</view>
					<view class="row mt20">
						<view class="mr20 br4 bg-FFB054-FF8901 px10 py5 c-w ft22" v-if="addressInfo.is_default">
							默认 
						</view>
						<view class="">
							<text>{{addressInfo.name}}</text><text class="ml20">{{addressInfo.mobile}}</text>
						</view>
					</view>
				</view>
				<view class="ml20">
					<u-icon name="arrow-right" color="#333" size="20"></u-icon>
				</view>
			</view>
			<view class="py30 row" v-else @tap="toAddressList">
				<view class="flex1 row flex-center">
					<image class="wh40" src="https://admin.hnyxtywh.com/images/img/icon_tianjia.png" mode=""></image>
					<view class="ml20 ft32">
						点击添加地址
					</view>
				</view>
				<view class="ml40">
					<u-icon name="arrow-right" color="#333" size="20"></u-icon>
				</view>
			</view>
		</view>
		
		<view class="p20 bgfff mt20">
			<view class="mar-top-20" v-for="(it,ix) in dataInfo.data" :key="ix">
				
				<view class="row mar-top-20" :class="index===0?'':'mt20'" v-for="(item,index) in it.cart_data" :key="index">
					<image class="wh160 br16 mr20" :src="item.image_text" mode=""></image>
					<view class="flex1">
						<view class="ft28">
							{{item.name}}
						</view>
						<view class="row j-sb a-center ft26 mt20">
							<view class="">
								{{item.sku_name?item.sku_name:''}}
							</view>
							<view class="">
								×{{item.num}}
							</view>
						</view>
						<view class="mt20 c-E23737 ft28">
							￥{{item.price}}
						</view>
					</view>
				</view>
			</view>
			<view class="mt10 py30 row j-sb a-center ft26 borb-F1F1F1">
				<view class="">
					商品金额
				</view>
				<view class="">
					￥{{dataInfo?.total_price_data?.goods_money}}
				</view>
			</view>
			<view class="py30 row j-sb a-center ft26 borb-F1F1F1">
				<view class="">
					运费
				</view>
				<view class="">
					￥{{dataInfo?.total_price_data?.pay_freight_money}}
				</view>
			</view>
			<view class="py30 row j-sb a-center ft26 borb-F1F1F1" v-if="is_vip">
				<view class="">
					会员优惠金额
				</view>
				<view class="">
					￥{{dataInfo?.total_price_data?.vip_money}}
				</view>
			</view>
			<view class="py30 row j-sb a-center ft26">
				<view class="">
					订单金额
				</view>
				<view class="">
					￥{{dataInfo?.total_price_data?.order_money}}
				</view>
			</view>
		</view>
		
		<view class="px20 py30 bgfff mt20 row a-center">
			<view class="mr40 ft26">
				订单备注
			</view>
			<view class="flex1">
				<input v-model="remark" class="text-align-right fontSize-26"   placeholder="选填" maxlength='-1' @blur="changeRemark"/>
			</view>
		</view>
		<view class="px20 py30 bgfff mt20 row a-center">
			<view class="mr40 ft26">
				可使用余额
			</view>
			<view class="flex1">
				<input v-model="money" class="text-align-right fontSize-26" disabled  placeholder="选填" maxlength='-1'/>
			</view>
		</view>
		
		<view class="px20 py30 bgfff mt20 row a-center">
			<view class="mr40 ft26">
				可使用积分
			</view>
			<view class="flex1">
				<input v-model="score" class="text-align-right fontSize-26" disabled  placeholder="选填" maxlength='-1'/>
			</view>
		</view>
		
		<view class="px20 py30 bgfff mt20">
			<view class="ft26 mb20">支付方式</view>
			<view class="row a-center">
				<view class="row a-center flex1" @tap="selectPayType(1)">
					<view class="wh30 mr20" :class="payType === 1 ? 'c-E23737' : 'c-999'">
						<u-icon :name="payType === 1 ? 'checkbox-fill' : 'checkbox'" size="20"></u-icon>
					</view>
					<text class="ft26" :class="payType === 1 ? 'c-E23737' : 'c-333'">微信支付</text>
				</view>
				<view class="row a-center flex1" @tap="selectPayType(2)" v-if="canUseScorePay" :class="isScoreInsufficient ? 'opacity-50' : ''">
					<view class="wh30 mr20" :class="payType === 2 ? 'c-E23737' : 'c-999'">
						<u-icon :name="payType === 2 ? 'checkbox-fill' : 'checkbox'" size="20"></u-icon>
					</view>
					<text class="ft26" :class="payType === 2 ? 'c-E23737' : 'c-333'">积分支付</text>
					<text class="ft22 c-999 ml10" v-if="isScoreInsufficient">(积分不足)</text>
				</view>
			</view>
		</view>
		
		<view class="width-100 pt20 pb80 bgfff fixed bottom0 left0 z-index10">
			<view class="row j-sb">
				<view class="py16 ml20">
					<text class="ft28">需支付：</text>
					<text class="ft32 c-E23737" v-if="payType === 1">￥{{dataInfo?.total_price_data?.pay_price}}</text>
					<text class="ft32 c-E23737" v-else>{{dataInfo?.total_price_data?.pay_price}}积分</text>
				</view>
				<view class="w200 py16 c-w ft32 buy_car br16 row flex-center mr32" 
					:class="(payType === 2 && isScoreInsufficient) ? 'opacity-50' : ''" 
					@tap="handlePay">
					{{payType === 1 ? '支付' : '积分支付'}}
				</view>
			</view>
		</view>
	</view>
</template>

<script setup lang="ts">
import { onLoad, onShow, onUnload } from '@dcloudio/uni-app';
import {userAddress,getsettlePage,subOrder,payOrder,payOrderWithScore} from '@/utils/api'
import { ref, computed } from 'vue';

// 声明微信支付相关类型
declare const WeixinJSBridge: any;
declare const wx: any;
const 	is_vip = ref(false),//是否为会员
		id = ref(),
		isSwitch = ref(2),//2自提1配送
		storeInfo = ref({
					name:'自提点',
					dist:'0',
				}),//自提点
		shop_id = ref(),
		addressInfo = ref({
			name:'',
			mobile:'',
			is_default:'',
			addr:'',
			address:'',
		}),//配送地址
		address_id = ref(),
		dataInfo = ref({}),
		remark = ref(),
		paying = ref(false),
		order_id = ref(),
		money = ref(),//可使用余额
		score = ref(),//可使用积分
		payType = ref(1)//支付方式 1=微信支付 2=积分支付

// 计算积分是否不足
const isScoreInsufficient = computed(() => {
	const payPrice = dataInfo.value?.total_price_data?.pay_price || 0;
	const userScore = score.value || 0;
	return userScore < payPrice;
})

// 计算是否支持积分支付（所有商品都必须是POS商品）
const canUseScorePay = computed(() => {
	if (!dataInfo.value?.data) return false;
	
	// 检查所有商品是否都支持积分支付
	for (const shop of dataInfo.value.data) {
		if (shop.cart_data) {
			for (const item of shop.cart_data) {
				if (!item.is_pos) {
					return false;
				}
			}
		}
	}
	return true;
})
	onLoad((p: any)=>{
		id.value = p.ids?p.ids:'';
		isSwitch.value = p.isSwitch?Number(p.isSwitch):2;
		
		is_vip.value = uni.getStorageSync('vip_status')===1?true:false;
		
		getAddressList();
	})
// 支付
const pay = async()=>{
	if(!paying.value){
		paying.value = true;
		
		// 积分支付
		if(payType.value === 2){
			await payWithScore();
			return;
		}
		
		// 微信支付
		let obj = {
			order_code:order_id.value,
		};
		console.log('obj',obj);
		const res = await payOrder(obj);
		if (res.code == 1) {
			// 检查是否有支付数据
			if (!res.data) {
				uni.showToast({
					title: '支付数据获取失败',
					icon: 'none'
				});
				return;
			}
			
			let data = JSON.parse(JSON.stringify(res.data))
			console.log(data, 'data')
			// 调用微信支付
			callWechatPayInGoodsBuy(data)
		}else if(res.code==2){
			uni.showToast({
				title: res.msg,
				icon: 'none'
			});
			setTimeout(() => {
				uni.redirectTo({
					url:'/mypages/orderlist/orderlist'
				})
			}, 1200)
		}else{
			uni.showToast({
				title: res.msg,
				icon: 'none'
			});
		}
	}else{
		paying.value = false;
		return ;
	}
}
// 提交订单
const btn = ref(false)
const handlePay=async()=>{
	if(btn.value){
		uni.showToast({
			title:'请勿频繁操作',
			icon:'error'
		})
		return
	}
	
	// 如果选择积分支付但积分不足，则不允许支付
	if(payType.value === 2 && isScoreInsufficient.value) {
		uni.showToast({
			title: '积分不足，无法使用积分支付',
			icon: 'none'
		});
		return;
	}
	// 提交订单
	let obj = {
		key:dataInfo.value.key,
		user_remarks:remark.value,
		pay_type:payType.value,
		money:dataInfo.value.total_price_data?.pay_price>money.value?money.value:dataInfo.value.total_price_data?.pay_price
	}
	let res = await subOrder(obj);
	if(res.code == 1){
		console.log(res,'res')
		order_id.value = res.data.order_code
		// 支付
		pay();
	}else{
		uni.showToast({
			title: res.msg,
			icon: 'none'
		});
	}
	setTimeout(()=>{
		btn.value = false
	},1000)
}
// 备注
const changeRemark=(e)=>{
	console.log(e);
	remark.value = e.detail.value;
}

// 选择支付方式
const selectPayType=(type)=>{
	// 如果选择积分支付但积分不足，则不允许选择
	if(type === 2 && isScoreInsufficient.value) {
		uni.showToast({
			title: '积分不足，无法使用积分支付',
			icon: 'none'
		});
		return;
	}
	payType.value = type;
}

// 积分支付
const payWithScore=async()=>{
	try {
		const res = await payOrderWithScore({
			order_code: order_id.value
		});
		
		// 后端返回 code=2 表示积分支付成功
		if(res.code === 2){
			uni.showToast({
				title: '积分支付成功',
				icon: 'success'
			});
			setTimeout(() => {
				uni.redirectTo({
					url:'/indexpages/paysuccess/paysuccess?type=2&order_id=' + order_id.value
				})
			}, 1200)
		} else {
			uni.showToast({
				title: res.msg || '积分支付失败',
				icon: 'none'
			});
		}
	} catch (error) {
		console.error('积分支付错误:', error);
		uni.showToast({
			title: '积分支付失败',
			icon: 'none'
		});
	} finally {
		paying.value = false;
	}
}
// 去切换地址
const toAddressList=()=>{
	uni.navigateTo({
		url:'/indexpages/addresslist/addresslist?t=1',
		success: (res) => {}
	})
}

// 监听地址选择事件
onShow(()=>{
	uni.$on('selectaddress',(data)=>{
		console.log('选择地址:', data);
		addressInfo.value = data;
		address_id.value = data.id;
		// 重新获取结算页面数据
		settlePage();
	})
})

// 页面卸载时移除事件监听
onUnload(()=>{
	uni.$off('selectaddress')
})
// 去添加地址
const toAddressAdd=()=>{
	uni.navigateTo({
		url:'/indexpages/addressadd/addressadd'
	})
}
// 获取数据
const settlePage=async()=>{
	let obj = {
		id:id.value,
		send_style:isSwitch.value,
		address_id:address_id.value,
		shop_id:shop_id.value,
	}
	let res = await getsettlePage(obj);
	if (res.code == 1) {
		console.log(res.data);
		dataInfo.value = res.data;
		money.value = res.data.user_money;
		score.value = res.data.user_score || 0;
	}else{
		if(res.msg.includes('不支持配送')){
			uni.showToast({
				title: res.msg,
				icon: 'none'
			})
			isSwitch.value = 2;
			// getShopList();
		}else if(res.msg.includes('不支持自提')){
			uni.showToast({
				title: res.msg,
				icon: 'none'
			})
			isSwitch.value = 1;
			getAddressList();
		}else{
			uni.showToast({
				title: res.msg,
				icon: 'none'
			})
		}
	}
}
// 地址列表
const getAddressList=async()=>{
	let obj = {}
	let res = await userAddress(obj);
	if (res.code == 1) {
		let address_list = res.data.address;
		if(address_list.some(it=>it.is_default===1)){
			addressInfo.value = address_list.filter(it=>it.is_default===1)[0];
			address_id.value = addressInfo.value.id;
		}
		settlePage();
	}else{
		uni.showToast({
			title: res.msg,
			icon: 'none'
		})
	}
}

// 调用微信支付
const callWechatPayInGoodsBuy = (payData: any) => {
	console.log('开始调用微信支付:', payData);
	console.log('WeixinJSBridge 存在:', typeof WeixinJSBridge !== 'undefined');
	console.log('wx 存在:', typeof wx !== 'undefined');
	
	// 等待微信环境加载完成
	const tryWechatPay = () => {
		if (typeof WeixinJSBridge !== 'undefined') {
			console.log('使用 WeixinJSBridge 调用微信支付');
			// 使用WeixinJSBridge调用微信支付
			WeixinJSBridge.invoke('getBrandWCPayRequest', {
				appId: payData.appId,
				timeStamp: payData.timeStamp,
				nonceStr: payData.nonceStr,
				package: payData.package,
				signType: payData.signType,
				paySign: payData.paySign
			}, (result: any) => {
				console.log('WeixinJSBridge 支付结果:', result);
				handlePayResultInGoodsBuy(result);
			});
		} else if (typeof wx !== 'undefined') {
			console.log('使用 wx.chooseWXPay 调用微信支付');
			// 使用微信JS-SDK的支付接口
			wx.chooseWXPay({
				timestamp: payData.timeStamp,
				nonceStr: payData.nonceStr,
				package: payData.package,
				signType: payData.signType,
				paySign: payData.paySign,
				success: (result: any) => {
					console.log('wx.chooseWXPay 支付成功:', result);
					handlePayResultInGoodsBuy({err_msg: 'get_brand_wcpay_request:ok'});
				},
				cancel: (result: any) => {
					console.log('wx.chooseWXPay 支付取消:', result);
					handlePayResultInGoodsBuy({err_msg: 'get_brand_wcpay_request:cancel'});
				},
				fail: (result: any) => {
					console.log('wx.chooseWXPay 支付失败:', result);
					handlePayResultInGoodsBuy({err_msg: 'get_brand_wcpay_request:fail'});
				}
			});
		} else {
			console.log('微信支付环境检查失败，等待加载...');
			// 如果微信环境还没加载完成，等待一下再试
			setTimeout(() => {
				if (typeof WeixinJSBridge !== 'undefined' || typeof wx !== 'undefined') {
					tryWechatPay();
				} else {
					uni.showToast({
						title: '请在微信中打开',
						icon: 'none'
					});
				}
			}, 1000);
		}
	};
	
	tryWechatPay();
}

// 处理支付结果
const handlePayResultInGoodsBuy = (result: any) => {
	paying.value = false;
	if (result.err_msg === 'get_brand_wcpay_request:ok') {
		uni.showToast({
			title: '支付成功',
			icon: 'success'
		});
		setTimeout(() => {
			uni.redirectTo({
				url:'/indexpages/paysuccess/paysuccess?type=2&order_id=' + order_id.value
			})
		}, 1200)
	} else if (result.err_msg === 'get_brand_wcpay_request:cancel') {
		uni.showToast({
			title: '您已取消支付',
			icon: 'none'
		});
		setTimeout(() => {
			uni.redirectTo({
				url:'/mypages/orderlist/orderlist'
			})
		}, 1200)
	} else {
		uni.showToast({
			title: '支付失败',
			icon: 'none'
		});
		setTimeout(() => {
			uni.redirectTo({
				url:'/mypages/orderlist/orderlist'
			})
		}, 1200)
	}
}
</script>

<style>
.buy_car{
	background: #C9951C;
}

.opacity-50 {
	opacity: 0.5;
}

.buy_car.opacity-50 {
	background: #ccc;
}
</style>
